package com.wesleyxie.mobile.android.todopomodoro.provider;

import static com.wesleyxie.mobile.android.todopomodoro.util.LogUtils.LOGW;
import static com.wesleyxie.mobile.android.todopomodoro.util.LogUtils.LOGD;
import static com.wesleyxie.mobile.android.todopomodoro.util.LogUtils.makeLogTag;

import com.wesleyxie.mobile.android.todopomodoro.provider.TodoContract.ListsColums;
import com.wesleyxie.mobile.android.todopomodoro.provider.TodoContract.TasksColumns;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class TodoDatabase extends SQLiteOpenHelper {
	private static final String TAG = makeLogTag(TodoDatabase.class);
	private static final String DATABASE_NAME = "todopomo.db";

	// NOTE: carefully update onUpgrade() when bumping database versions 
	// to make sure user data is saved.
	private static final int DATABASE_VERSION = 1;

	interface Tables {
		String TASKS = "tasks";
		String LISTS = "lists";
	}
	
	public TodoDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + Tables.TASKS + " ("
                + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + TasksColumns.TASK_ID + " TEXT NOT NULL,"
                + TasksColumns.TASK_TITLE + " TEXT NOT NULL,"
                + TasksColumns.TASK_DESC + " TEXT,"
                + TasksColumns.TASK_END + " TEXT,"
                + TasksColumns.TASK_STATUS + " INTEGER NOT NULL,"
                + TasksColumns.TASK_BELONG_TO + " TEXT NOT NULL,"
                + "UNIQUE (" + TasksColumns.TASK_ID + ") ON CONFLICT REPLACE)");
		
		db.execSQL("CREATE TABLE " + Tables.LISTS + " ("
                + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + ListsColums.LIST_ID + " TEXT NOT NULL,"
                + ListsColums.LIST_TITLE + " TEXT NOT NULL,"
                + "UNIQUE (" + ListsColums.LIST_ID + ") ON CONFLICT REPLACE)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);

		if (oldVersion != DATABASE_VERSION) {
			LOGW(TAG, "Destroying old data during upgrade");

			db.execSQL("DROP TABLE IF EXISTS " + Tables.TASKS);
			db.execSQL("DROP TABLE IF EXISTS " + Tables.LISTS);

			onCreate(db);
		}
	}
	
	public static void deleteDatabase(Context context) {
        context.deleteDatabase(DATABASE_NAME);
    }
}
